/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.hyjiacan.deadqq.server.listener;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.hyjiacan.deadqq.common.entity.User;
import org.hyjiacan.deadqq.server.Server;
import org.hyjiacan.deadqq.server.dao.UserDAO;

/**
 *
 * @author hyjiacan
 */
public class LoginListener implements Runnable {
    private ServerSocket socket;
    private BufferedReader br;
    private ObjectInputStream ois;

    @Override
    public void run() {
        while (true) {
            try {
                if (socket == null) {
                    socket = new ServerSocket(Server.LOG_PORT);
                }
                System.out.println("开始监听登录");
                Socket s = socket.accept();
                System.out.println("客户端已经连接，等待数据读取");
                ObjectInputStream ois = new ObjectInputStream(
                        s.getInputStream());
                User u = (User) ois.readObject();
                System.out.println("数据读取完成");
                System.out.println("账号:" + u.getNumber() + "==="
                        + u.getPassword() + "正在登录");

                ObjectOutputStream oos = new ObjectOutputStream(
                        s.getOutputStream());
                boolean state = false;
                System.out.println("查找用户数据");
                User user = new UserDAO().query(u.getNumber());
                if (user != null && user.getPassword().equals(u.getPassword())) {
                    state = true;
                }
                oos.writeBoolean(state);
                oos.flush();

                if (state) {
                    oos.writeObject(user);
                    oos.flush();
                } else {
                    System.out.println("找不到帐号" + u.getNumber());
                }



            } catch (java.net.BindException e) {
                System.err.println("端口" + Server.LOG_PORT + "被占用");
                return;
            } catch (IOException | ClassNotFoundException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE,
                        null, ex);
                System.err.println(ex);
            } finally {
                try {
                    if (ois != null) {
                        ois.close();
                    }
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException ex) {
                    Logger.getLogger(LoginListener.class.getName()).log(
                            Level.SEVERE, null, ex);
                }
            }
        }
    }
}
